<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-input placeholder="请输入姓名" style="width: 200px" v-model="params.name" clearable></el-input>
      <el-button type="warning" style="margin-left: 10px" @click="findBySearch()">查询</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="add()">新增</el-button>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'judDate', order: 'descending' }">
        <el-table-column prop="judUsername" label="用户名" width="270"></el-table-column>
        <el-table-column prop="judName" label="昵称" width="270"></el-table-column>
        <el-table-column prop="judRole" label="角色" width="270">
          <template slot-scope="scope">
            {{ scope.row.judRole === 0 ? '管理员' : '评委' }}
          </template>
        </el-table-column>
        <el-table-column prop="judState" label="状态" width="270">
          <template slot-scope="scope">
            {{ scope.row.judState === 0 ? '禁用' : '启用' }}
          </template>
        </el-table-column>
        <el-table-column prop="judDate" label="创建时间" sortable width="350"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger" style="margin-left: 5px">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-left: 50%; margin-top: 10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4"
        :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </div>
    <div>
      <!-- Form -->
      <el-dialog title="请填写信息" :visible.sync="dialogFormVisible" width="30%">
        <el-form :model="form" ref="formRef" label-width="15%" :rules="rules" :inline-message="true">
          <el-form-item label="用户名" prop="judUsername">
            <el-input v-model="form.judUsername" placeholder="字母和数字4-10位" autocomplete="off"
              style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="judPassword" label-width="15%">
            <el-input v-model="form.judPassword" placeholder="请输入密码（含字母大小写4-12位）" autocomplete="off" style="width: 90%"
              type="password" :show-password="showPassword" @suffix-click="togglePassword"
              suffix-icon="el-icon-eye-off"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="judName">
            <el-input v-model="form.judName" autocomplete="off" placeholder="请输入昵称" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="judRole">
            <el-select v-model="form.judRole" placeholder="请选择角色" style="width: 90%">
              <el-option label="管理员" value="0">管理员</el-option>
              <el-option label="评委" value="1">评委</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="judState">
            <el-radio v-model="form.judState" label="0">禁用</el-radio>
            <el-radio v-model="form.judState" label="1">启用</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Judgescore",
  data() {
    return {
      params: {
        name: '',
      },
      currentPage4: 1,
      pageSize: 10,
      tableData: [],
      dialogFormVisible: false,
      form: {
        judUsername: '',
        judPassword: '',
        judName: '',
        judRole: '',
        judState: '',
        judDate: ''
      },
      total: 0, // 总条数，用于分页
      rules: {
        judUsername: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{4,10}$/, message: '用户名必须是字母和数字组合，长度在4到10之间', trigger: 'blur' }
        ],
        judPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{4,12}$/, message: '密码必须包含大小写字母和数字，长度在4到12之间', trigger: 'blur' }
        ],
        judName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        judRole: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        judState: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      showPassword: false,
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      request.get("/judge/list", {
        params: { page: this.currentPage4, size: this.pageSize }
      }).then(res => {
        if (res.code === 1) {
          const start = (this.currentPage4 - 1) * this.pageSize;
          const end = start + this.pageSize;
          this.tableData = res.data.slice(start, end);  // 根据页码和每页显示的数量动态截取数据
          this.total = res.data.length > 0 ? res.data[0].total : 0; // 计算总条数
        } else {
          // 处理错误情况
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      });
    },

    findBySearch() {
      request.get("/judge/search", {
        params: this.params,
      }).then(res => {
        if (res.code === 1) {
          const start = (this.currentPage4 - 1) * this.pageSize;
          const end = start + this.pageSize;
          this.tableData = res.data.slice(start, end);  // 根据页码和每页显示的数量动态截取数据
          this.total = res.data.length > 0 ? res.data[0].total : 0; // 计算总条数
        } else {
          this.$message({
            message: "查询失败",
            type: 'error'
          });
        }
      });
    },


    add() {
      this.form = {}; // 新增数据的时候清空数据
      this.dialogFormVisible = true;
    },
    edit(obj) {
      this.form = { ...obj }; // 使用对象展开运算符避免引用问题
      this.dialogFormVisible = true;
    },
    togglePassword() {
      this.showPassword = !this.showPassword; // 切换显示/隐藏状态
    },
    del(id) {
      request.delete(`/judge/${id}`).then(res => {
        if (res.code === 1) {
          this.tableData = this.tableData.filter(item => item.id !== id);
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      });
    },
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          request.post("/judge/save", this.form).then(res => {
            if (res.code === 1) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.load();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage4 = 1; // 切换每页显示数量时，重置为第一页
      this.load();
    },
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.load();
    },
  },
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 10px;
  /* 减少表单项之间的间距 */
}

.el-form-item__error {
  color: red;
  /* 统一错误提示颜色 */
  font-size: 12px;
  /* 统一错误提示字体大小 */
  line-height: 1.2;
  /* 统一错误提示行高 */
  position: absolute;
  /* 绝对定位，确保错误提示显示在表单项下方 */
  top: 100%;
  /* 确保错误提示显示在表单项下方 */
  left: 0;
  /* 左对齐 */
  padding-top: 4px;
  /* 上边距 */
}

.el-form-item.is-error .el-input__inner {
  border-color: red;
  /* 输入框错误时的边框颜色 */
}

.el-form-item.is-error .el-select .el-input__inner {
  border-color: red;
  /* 下拉选择框错误时的边框颜色 */
}
</style>
